package main.java.com.waylau.netty.demo.time.optimize;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * 作者  Administrator
 * 时间  2017/6/23 17:59
 * 文件  nettydemo
 * 描述  每次只读四个字节 从头开始
 * 1. 起点不能错
 * 2. 字节长度不能错 这里是4个
 */
public class TimeClient2 {
	public static void main(String[] args) {
		NioEventLoopGroup workgroup = new NioEventLoopGroup();
		try {
			Bootstrap b =  new Bootstrap();
			b.group(workgroup) // 事件栈
			 .channel(NioSocketChannel.class)
			 .option(ChannelOption.SO_KEEPALIVE,true)
			 .handler(new ChannelInitializer<SocketChannel>() {
				 @Override
				 protected void initChannel(SocketChannel ch) throws Exception {
				   // 连接成功后 走这个回调方法
					ch.pipeline().addLast(new TimeClientHandler1());
				 }
			 });
			// 连接客户端
			try {
				ChannelFuture f = b.connect("localhost", 8080).sync();
				f.channel().closeFuture().sync();// 等待被关闭
			} catch (InterruptedException e) {
				e.printStackTrace();
				System.out.println("连接失败");
			}

		}finally {
			workgroup.shutdownGracefully();
		}

	}
}
